package server

import (
	"fmt"
	"net/http"
	"time"

	"github.com/hyperledger/fabric-sdk-go/pkg/client/channel"
)

func Hello(w http.ResponseWriter, r *http.Request) {
	_, _ = w.Write([]byte("Hello world!"))
}

func (app *Application) query_obj(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	id := r.URL.Query().Get("ID")
	_, _ = w.Write([]byte("<-查询对象ID为: '" + id + "'的对象哈希-> "))
	response, err := app.SdkEnvInfo.Client.Query(channel.Request{ChaincodeID: app.SdkEnvInfo.ChaincodeID, Fcn: "ReadObject", Args: [][]byte{[]byte(id)}})
	if err != nil {
		fmt.Println(err)
		_, _ = w.Write([]byte(err.Error()))
	} else {
		_, _ = w.Write([]byte(string(response.Payload)))
		fmt.Printf("<-查询对象ID为: '%s'的对象哈希-> %s\n", id, string(response.Payload))
	}
}

func (app *Application) add_obj(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()
	obj := Object{
		ID:   r.FormValue("ID"),
		Hash: r.FormValue("Hash"),
	}
	timeStart := time.Now().UnixNano()
	response, err := app.SdkEnvInfo.Client.Execute(channel.Request{ChaincodeID: app.SdkEnvInfo.ChaincodeID, Fcn: "CreateObject", Args: [][]byte{[]byte(obj.ID), []byte(obj.Hash)}})
	fmt.Println("add_obj cost: ", time.Now().UnixNano()-timeStart)
	if err != nil {
		fmt.Println(err)
		_, _ = w.Write([]byte("<-添加对象ID: '" + obj.ID + "', Hash: '" + obj.Hash + "'到Fabric失败->" + err.Error()))
	} else {
		fmt.Printf("<-添加对象ID: '%s', Hash: '%s'到Fabric->\n", obj.ID, obj.Hash)
		_, _ = w.Write([]byte("<-添加对象ID: '" + obj.ID + "', Hash: '" + obj.Hash + "'到Fabric->" + string(response.Payload)))
	}

}

func ServiceStart(app Application) {
	http.HandleFunc("/", Hello)
	http.HandleFunc("/get", app.query_obj)
	http.HandleFunc("/put", app.add_obj)

	err := http.ListenAndServe(":9000", nil)
	if err != nil {
		panic(err)
	}
}
